/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia.controller.jpa;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import oracle.toplink.essentials.exceptions.DatabaseException;

/**
 *
 * @author Novo usuário
 */
public class JdbcController {

    private EntityManagerFactory emf = null;
    String user = "victorinfo";
    String pwd = "qw34rt";
    String ip = "mysql.victorinfo.com.br";
    String porta = "3306";
    String driver = "com.mysql.jdbc.Driver";
    private String schema;
    private static JdbcController instance = new JdbcController();

    public static JdbcController getInstance() {
        return instance;
    }

    private JdbcController() {

    }

    public EntityManager getEntityManager() {
        if (schema == null || schema.isEmpty()) {
            return null;//throw new Exception("É necessário um esquam de banco para inicializar a aplicação");
        }
        try {
            if (emf == null) {
                Properties prop = new Properties();
                prop.setProperty("toplink.jdbc.user", user);
                prop.setProperty("toplink.jdbc.password", pwd);
                prop.setProperty("toplink.jdbc.url", "jdbc:mysql://" + ip + ":" + porta + "/" + schema);
                prop.setProperty("toplink.jdbc.driver", driver);
                prop.setProperty("toplink.logging.level", "FINE");
                //prop.setProperty("toplink.ddl-generation", "create-tables");
                emf = Persistence.createEntityManagerFactory("MearchPersistencePU", prop);
                return emf.createEntityManager();
            }
        } catch (DatabaseException ex) {
            emf = null;
            try {
                Class.forName(driver);
                Connection con = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + porta, user, pwd);
                Statement stmt = con.createStatement();
                stmt.execute("create database " + schema);
                stmt.close();
                con.close();
            } catch (SQLException ex1) {
                Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex1);
            } catch (ClassNotFoundException ex1) {
                Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex1);
            }
            return getEntityManager();
        }
        return emf.createEntityManager();
    }

    public String getSchemanameFormatado() {
        if(schema == null){
            return "";
        }
        return " - " + schema;
    }

    public void deleteSchemaCurrent(){
         try {
            Class.forName(driver);
            Connection con = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + porta, user, pwd);
            Statement stmt = con.createStatement();
            stmt.execute("drop database " + schema);
            schema = null;
            emf.close();
            stmt.close();
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public List<String> listSchemas() {
        List<String> dbs = new ArrayList<String>();
        try {
            Class.forName(driver);
            Connection con = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + porta, user, pwd);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("show databases");
            while (rs.next()) {
                String db = rs.getString(1);
                if (!db.equals("information_schema") && !db.equals("mysql") && !db.equals("test")) {
                    dbs.add(db);
                }
            }
            rs.close();
            stmt.close();
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JdbcController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return dbs;
    }

    public void disconnect(){
        if (emf != null) {
            emf.close();
            emf = null;
        }
        schema = null;
    }

    /**
     * @return the schema
     */
    public String getSchema() {
        return schema;
    }

    /**
     * @param schema the schema to set
     */
    public void setSchema(String schema) {
        if (emf != null) {
            emf.close();
            emf = null;
        }
        this.schema = schema;
    }
}
